#!/usr/bin/env bash

# SYNOPSIS
#   poor-man's daemon: nohup doing & &> /dev/null
#   log entry: doing [what you're doing]
# ------------------------------------------

haz() {
  command -v "$1" > /dev/null 2>&1
}

logfile="$HOME/.doing"

if ! haz notify-send || ! haz xdotool || ! haz xwininfo; then
  printf "[$(tput setaf 1)ERROR$(tput sgr0)] Unable to find all dependencies"
  exit 1;
fi

# logging daemon
if (( $# == 0 )); then
  while ((1)); do
    _prog=$(cat /proc/$(xdotool getwindowpid $(xdotool getwindowfocus))/comm)
    _wintitle=$(xwininfo -root -children | grep $(printf '%x' $(xdotool getwindowfocus)) | grep -oEi '"[^"]+"' | head -1 | tr -d '"')
    _weather=$(weathermajig boulder)
    _date=$(date +'%Y-%m-%d %H:%M:%S')
    # date/time | weather | program | window title
    echo "$_date | $_weather | $_prog | $_wintitle" >> "$logfile"
    unset _prog _wintitle _weather _date
    sleep 1800;
  done;
  exit 0;
fi

if [[ $1 == "--show" ]]; then
  cat $logfile | column -s '|' -t
  exit 0
fi

if [[ $1 == "--debug" ]]; then
  while ((1)); do
    _prog=$(cat /proc/$(xdotool getwindowpid $(xdotool getwindowfocus))/comm)
    _wintitle=$(xwininfo -root -children | grep $(printf '%x' $(xdotool getwindowfocus)) | grep -oEi '"[^"]+"' | head -1 | tr -d '"')
    _weather=$(weathermajig boulder --short)
    _date=$(date +'%Y-%m-%d %H:%M:%S')
    # date/time | weather | program | window title
    echo "$_date | $_weather | $_prog | $_wintitle"
    unset _prog _wintitle _weather _date
    sleep 5
  done;
  exit 0
fi
